package com.yj.auto.core.jfinal.interceptor;

import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;

import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;
import com.jfinal.kit.StrKit;
import com.yj.auto.Constants;
import com.yj.auto.core.base.online.SessionUser;
import com.yj.auto.core.base.online.SessionUserUtil;
import com.yj.auto.helper.LogHelper;
import com.yj.auto.utils.NetUtil;

/**
 * 是否登录用户
 * 
 */
public class SessionUserInterceptor implements Interceptor {

	private Pattern pattern;

	public SessionUserInterceptor(String regex) {
		this(regex, true);
	}

	public SessionUserInterceptor(String regex, boolean caseSensitive) {
		if (StrKit.isBlank(regex))
			throw new IllegalArgumentException("regex can not be blank.");
		pattern = caseSensitive ? Pattern.compile(regex) : Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
	}

	public void intercept(final Invocation inv) {
		Controller c = inv.getController();
		HttpServletRequest request = c.getRequest();
		String uri = getUri(request.getContextPath(), request.getRequestURI());
		if (pattern.matcher(uri).matches()) {// 无需登录验证
			inv.invoke();
		} else {
			if (Constants.SYS_SAVE_ACCESS_LOG) {// 添加访问日志
				LogHelper.addAccessLog(request);
			}

			SessionUser su = SessionUserUtil.getSessionUser(request);
			if (null == su) {// 未登录
				if (NetUtil.isAjax(request)) {// ajax请求
					c.getResponse().setHeader("session-status", "timeout");
				} else {
					String index = "/" + Constants.SYS_INDEX_URI;
					c.redirect(index);
				}
			} else {// 已登录
				inv.invoke();
			}
		}
	}

	private String getUri(String contextpath, String url) {
		if (null == contextpath || "".equals(contextpath))
			return url;
		return url.substring(url.indexOf(contextpath) + contextpath.length());
	}

}
